<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>完整写法</title>
    <script src="/vue.js"></script>
  </head>
  <body>
    <div id="app">
      <div>
        <p>{{number.a}}</p>
        <button @click="changeA()">changeA</button>
      </div>
      <div>
        <p>{{number.b}}</p>
        <button @click="changeB()">changeB</button>
      </div>
    </div>
    <script type="text/javascript">
      Vue.config.productionTip = false;
      const vm = new Vue({
        el: "#app",
        data: {
          number: {
            a: 1,
            b: 1,
          },
        },
        methods: {
          changeA() {
            this.number.a++;
          },
          changeB() {
            this.number.b++;
          },
        },
        watch: {
          // 监听多级结构中某个属性的变化
          "number.a": {
            handler(newValue, oldValue) {
              console.log(newValue, oldValue);
            },
          },
          "number.b": {
            handler(newValue, oldValue) {
              console.log(newValue, oldValue);
            },
          },
          number: {
            // 监听多级结构中所有属性的变化, 对一个对象或者数组监视的时候,内部发送改变并不能触发handler 需要开启深度监视
            deep: true,
            handler(newValue, oldValue) {
              console.log(newValue, oldValue);
            },
          },
          // wacth默认只能监视某个属性的变化,并不能在初始化的时候就执行handler函数
          //可以配置immediate属性,让watch在初始化阶段就立即监视
          // immediate: true,
        },
      });
    </script>
  </body>
</html>
